package org.adorsys.aderp.jpa.api.audit;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;


public abstract class AbstractAuditRecordBuilder implements AuditRecordBuilder {

	/**
	 * Implementation will provide the name of the actual user from the security context.
	 * 
	 * @return
	 */
	public abstract String getUserName();
	
	@Override
	public <AR extends AbstractAuditRecord> AR buildRecord(String businessKey,
			Object entity, Class<AR> recordKlass) {
		
		AR t;
		try {
			t = recordKlass.newInstance();
		} catch (InstantiationException e) {
			throw new IllegalArgumentException("Can not use default constructor to instantiate class: " + recordKlass, e);
		} catch (IllegalAccessException e) {
			throw new IllegalArgumentException("Can not use default constructor to instantiate class: " + recordKlass, e);
		}
		t.setEntityKey(businessKey);
		t.setEntityName(entity.getClass().getName());
		String userName = getUserName();
		if(StringUtils.isBlank(userName)){
			t.setModifyingUser("anonymous");
		} else {
			t.setModifyingUser(getUserName());
		}
		Date now = new Date();
		t.setModifOn(now);
		t.setRecordKey(businessKey + "_" + now.getTime());
		return t;
	}

}
